<?php
// +----------------------------------------------------------------------
// | ThinkPHP
// +----------------------------------------------------------------------
// | Copyright (c) 2007 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: sunlf <sunlf@gmail.com>
// +----------------------------------------------------------------------
/**
 * 获取用户信息
 */
function getUserInfo($uid){
	$uid = $uid ? $uid : Session::getLocal('id');
	if($uid) $user = M("User")->find($uid);
	return $user;
}

/**
 * 获取logo图片
 */
function getLogoImg($url){
	if(is_numeric($url)){
		$info = M("BaseBrand")->find($url);
		$url = $info['brand_img'];
	}
	if($url){
		return $url;
	}else{
		return __ROOT__."/Public/images/default_logo.gif";
	}
}
/**
 * 获取商品图片
 * @param $url
 */
function getCommodityImg($url){
	if($url){
		return $url;
	}else{
		return __ROOT__."/Public/images/default_products.gif";
	}

}

//行业大类
function getIndustry($str=''){
	$arr1 = array("1"=>"个人用品","2"=>"办公器材","3"=>"家居生活","4"=>"家电数码","5"=>"汽车天地");
	$arr2 = array_flip($arr1);
	if(!$str) return $arr1;
	if(is_numeric($str)){
		return $arr1[$str];
	}else{
		return $arr2[$str];
	}
}

/**
 * 获取某个表的某条数据的某个字段的值
 * @param unknown_type $id
 * @param unknown_type $table
 * @param unknown_type $field
 */
function getAssignInfo($id,$table,$field){
	$map['id'] = $id;
	$info = M($table)->where($map)->find();
	return $info[$field];
}


/**
 +----------------------------------------------------------
 * 字符串截取，支持中文和其他编码
 +----------------------------------------------------------
 * @static
 * @access public
 +----------------------------------------------------------
 * @param string $str 需要转换的字符串
 * @param string $start 开始位置
 * @param string $length 截取长度
 * @param string $charset 编码格式
 * @param string $suffix 截断显示字符
 +----------------------------------------------------------
 * @return string
 +----------------------------------------------------------
 */
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true)
{
    $str = strip_tags(html_entity_decode($str));
    $str = trim(str_replace("&nbsp;","",str_replace("\n","",str_replace("\r","",$str))));
    if(function_exists("mb_substr")){
        return mb_substr($str, $start, $length, $charset);
    }elseif(function_exists('iconv_substr')) {
        return iconv_substr($str,$start,$length,$charset);
    }
    $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
    $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
    $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
    $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
    preg_match_all($re[$charset], $str, $match);
    $slice = join("",array_slice($match[0], $start, $length));
    if($suffix) return $slice;
    return $slice;
}


/**
 * 信息提示alert方式
 * @param unknown_type $msg
 * @param unknown_type $url
 */
function showMsg($msg, $url){
	echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />";
	if($msg){
		echo "<script>alert('$msg');</script>";
	}
	if($url){
		echo "<script>location.href='$url'</script>";
		exit;
	}else{
		echo "<script>history.go(-1);</script>";
		exit;
	}
}
//UBB代码及其他替换
function ubb($text) {
	$text = html_entity_decode($text);
	$content = $text;
	//砍掉视频
//	$text = get_video($content);
//	if(!$text){
		$text = get_pic($content);
//	}
	$p= array(
	'/\[F l=(.*?)\](.*?)\[\/F\]/ie',
	'/\[V h=(.*?) p=(.*?) l=(.*?)\](.*?)\[\/V\]/i',
	'/\[V h=(.*?) p=(.*?)\](.*?)\[\/V\]/i',
	'/\[M\](.*?)\[\/M\]/i',
	'/\[T\](.*?)\[\/T\]/ie',
	'/\[VT (.*?)\](.*?)\[\/VT\]/i',
	);
	$rand=randStr(6);
	$r=array(
	"ubbpic('\\1','\\2','in')",
	"<a href='javascript:void(0);' onclick='showFlashDIV(\"$1\",\"$2\",\"$4\",\"".$rand."\",\"video\",this,\"$3\")' class='morelink'>$3<span class='linkvideo'>&nbsp;</span></a>&nbsp;",
	"<div class='media'><img id='img_".$rand."' style='background:url($2) no-repeat;' src='".__PUBLIC__."/images/feedvideoplay.gif' alt='play' onclick=\"showFlash('$1','$3',this,'".$rand."');\"/></div>",
	"<a href='javascript:void(0);' onclick='showFlashDIV(\"$1\",\"\",\"\",\"".$rand."\",\"music\",this,\"$1\")' class='morelink'>$1<span class='linkmusic'>&nbsp;</span></a>&nbsp;",
	"ubbtopicrl('\\1',1)",
	"<a href='javascript:void(0);' onclick='showVoteDIV(\"$1\",this)' class='morelink'>$2<span class='linkvote'>&nbsp;</span></a>&nbsp;",
	);
	$text=preg_replace($p,$r,$text);
	return '<li class="unlight">'.$text.'</li>';
}
function randStr($len=6) {
    $chars='ABDEFGHJKLMNPQRSTVWXY123456789';
    mt_srand((double)microtime()*1000000*getmypid());
    $password='';
    while(strlen($password)<$len)
    $password.=substr($chars,(mt_rand()%strlen($chars)),1);
    return $password;
}
//判断富媒体
function ismedialine($stringlink) {
	$vidoLink = parse_url($stringlink);
	$vido_host = get_host($vidoLink['host']);
	$ReturnMusic = preg_match("/\.(mp3|wma)$/i", $stringlink);
	$ReturnHost = preg_match("/(youku\.com|ku6\.com|sohu\.com|mofile\.com|sina\.com\.cn|tudou\.com|youtube\.com)$/i", $vido_host);
	preg_match_all("/".str_replace('/','\\/',ET_URL)."\/vote\/([0-9]*)$/i", $stringlink,$ReturnVote);
	return array('music'=>$ReturnMusic,'video'=>$ReturnHost,'vote'=>intval($ReturnVote[1][0]));
}
//share functions
function get_host($str){
	$list=array(
        "sina.com.cn",
        "youku.com",
        "tudou.com",
        "ku6.com",
        "sohu.com",
        "mofile.com",
        "youtube.com",
	);
	foreach($list as $v){
		if( strpos($str,$v)>0){
			$re= substr($str,strpos($str,$v),100);
			break;
		}
	}
	return $re;
}

function get_video($content){
	$matchstr='~(?:https?\:\/\/)((?:[A-Za-z0-9\_\-]+\.)+[A-Za-z0-9\:]{1,10}|localhost)(?:\/[\w\d\/=\?%\-\&_\~\`\@\[\]\:\+\#\.]*(?:[^\<\>\'\"\n\r\t\s\x7f-\xff])*)?~';
	preg_match_all($matchstr,$content,$match);
	if ($match[0]) {
		foreach ($match[0] as $stringlink) {
			$stringlink = str_replace('[/U]','',$stringlink);
			$medialink=ismedialine($stringlink);
			if($medialink['video']) {
				$getvideo=getvideothumb($stringlink);
				if ($getvideo['key']) {
					$returnImage=$returnImage?$returnImage:__PUBLIC__.'/images/video.gif';
					$share="[V h={$getvideo['host']} p={$getvideo['thumb']} l={$stringlink}]{$getvideo['key']}[/V]";
					$content=str_replace($stringlink,$share,$content);
					$type='media';
				}
			} else {
				if($medialink['music']) {
					$share="[M]{$stringlink}[/M]";
					$type='media';
				} else if($medialink['vote']) {
					$share="[VT {$medialink['vote']}]{$stringlink}[/VT]";
					$type='vote';
				}
				if ($share) {
					$content=str_replace($stringlink,$share,$content);
				}
			}
			if($share){
				break;
			}
		}
	}
	return $share;
//	return $content;
}

function get_content($text){
	$matchstr='~(?:https?\:\/\/)((?:[A-Za-z0-9\_\-]+\.)+[A-Za-z0-9\:]{1,10}|localhost)(?:\/[\w\d\/=\?%\-\&_\~\`\@\[\]\:\+\#\.]*(?:[^\<\>\'\"\n\r\t\s\x7f-\xff])*)?~';
	preg_match_all($matchstr,$text,$match);
	if ($match[0]) {
		foreach ($match[0] as $stringlink) {
			$stringlink = str_replace('[/U]','',$stringlink);
			$medialink=ismedialine($stringlink);
			$text=str_replace($stringlink,$share,$text);
		}
	}
	return $text;
}
function get_pic($content){
	$size = 3;
	$regexp = '/(<img[^>]*src=[^\"\']*[\"\']?([^>\'\"\s]*[\.gif|\.psd|\.raw|\.tga|\.pcx|\.tiff|\.jpg|\.bmp])[\"\']?[^>]*)/i';
	preg_match_all($regexp, $content, $match);
    //图片地址
	$share = '';
	$i = 0;
	if ($match[2]) {
		foreach ($match[2] as $stringlink) {
			$filename = basename($stringlink);
			$thumb = str_replace($filename,'thumb_'.$filename,$stringlink);
			if(!file_exists($thumb)){
				$thumb = $stringlink;
			}
			$img = '[F l='.$stringlink.']'.$thumb.'[/F]';
			if ($img) {
				$share .= $img;
				$i ++;
			}
			if($i>=$size){
				break;
			}
		}
	}
	return $share;
}

function getvideothumb($stringlink) {
    $vidoLink = parse_url($stringlink);
    $vido_host = get_host($vidoLink['host']);
    if('youku.com' == $vido_host){
        $youku = file_get_contents($stringlink);
        preg_match_all("/<li class=\"download\"(.*)<\/li>/",$youku,$match2);
        preg_match_all("/id\_(\w+)[=.]/",$stringlink,$matches);//http://v.youku.com/v_show/id_XMjYwNTExOTU2.html
        if(empty($matches[1][0])){//http://v.youku.com/v_playlist/f6020209o1p0.html
            preg_match_all("/iku\:\/\/\|video\|http\:\/\/v.youku.com\/v_show\/id\_(.*?)\.html/",$match2[1][0],$matches);
        }
        if(!empty($matches[1][0])) {
            $returnlink = $matches[1][0];
        }
        preg_match("/\|(http\:\/\/g\d\.ykimg\.com\/[^\|]+)\|/",$match2[1][0],$imageurl);
        if (!$imageurl[1]) {
            preg_match_all('/<a title="转发至新浪微博"(.*?)href="(.*?)pic=(.*?)"(.*?)>/',$youku,$match3);
            $returnImage = $match3[3][0];
        } else {
            $returnImage = $imageurl[1];
        }
    } elseif('tudou.com' == $vido_host) {
        $tudou = file_get_contents($stringlink);
        $tudou = iconv('gbk','utf-8//IGNORE',$tudou);
        preg_match_all("/view\/([\w])/",$stringlink,$matches);//http://www.tudou.com/programs/view/H4NhH5nvSgs/
        preg_match_all("/thumbnail = pic = '(.*?)'/",$tudou,$imageurl); //,thumbnail = pic = 'http://i3.tdimg.com/094/109/402/m25.jpg'
        if(empty($matches[1][0])){
            preg_match_all('/icode\:"(.*?)"/',$tudou,$matches);//http://www.tudou.com/playlist/p/l12038429.html
            preg_match_all('/pic\:"(.*?)"/',$tudou,$imageurl);
        }
        if(!empty($matches[1][0])) {
            $returnlink = $matches[1][0];
        }
        $returnImage = $imageurl[1][0];
    } elseif('ku6.com' == $vido_host) {
        $ku6 = file_get_contents($stringlink);
        $ku6 = iconv('gbk','UTF-8',$ku6);
        preg_match_all("/$ns.href = 'http\:\/\/v.ku6.com\/special\/show_([\w\-]+)\/([\w\-]+).html'/", $ku6,$matches);//all
        if(!empty($matches[2][0])) {
            $returnlink = $matches[2][0];
        }
        preg_match_all("/<span class=\"s_pic\">(.*)<\/span>/",$ku6,$imageurl);
        $returnImage = $imageurl[1][0];
    } elseif('mofile.com' == $vido_host){
        preg_match_all("/\/([\w\-]+)\.shtml/",$stringlink,$matches);
        if(!empty($matches[1][0])) {
            $returnlink = $matches[1][0];
        }
        $mofile = file_get_contents($stringlink);
        preg_match_all("/thumbpath=\"(.*?)\";/i",$mofile,$imageurl);
        $returnImage = $imageurl[1][0];
    } elseif('sina.com.cn' == $vido_host) {
        preg_match_all("/\/(\d+)\-(\d+)\.html/i",$stringlink,$matches);//http://video.sina.com.cn/v/b/51187154-1854900491.html
        $sina = file_get_contents($stringlink);
        preg_match_all("/pic: \'(.*?)\',/i",$sina,$imageurl);
        $returnImage = $imageurl[1][0];
        if(empty($matches[1][0])){
            if ($vidoLink['host']=='video.sina.com.cn') {//http://video.sina.com.cn/p/news/c/v/2011-05-02/131861328229.html
                preg_match_all("/swfOutsideUrl:\'http:\/\/you.video.sina.com.cn\/api\/sinawebApi\/outplayrefer.php\/vid=(.*?)\/s\.swf\',/i", $sina, $matches);
                preg_match_all("/pic: \'(.*?)\',/i",$sina,$imageurl);
                $returnImage = $imageurl[1][0];
            } else if ($vidoLink['host']=='tv.video.sina.com.cn') {//http://tv.video.sina.com.cn/play/95177.html
                preg_match_all("/\/(\d+)\.html/i", $stringlink, $matches);
                preg_match_all("/onerror=\"this.src=\'(.*?)\'\"/i",$sina,$imageurl);
                $returnImage = $imageurl[1][0];
            }
        }
        if(!empty($matches[1][0])) {
            $returnlink = $matches[1][0];
        }
    } elseif('sohu.com' == $vido_host) {
        preg_match_all("/\/(\d+)\/"."*$/",$stringlink,$matches);
        if(!empty($matches[1][0])) {
            $returnlink = $matches[1][0];
        }
    } elseif('youtube.com' == $vido_host) {
        //http://www.youtube.com/watch?v=oyi3_IDM2Kk
        preg_match_all("/watch\?v=([\w\-]+)/",$stringlink,$matches);
        if(!empty($matches[1][0])) {
            $returnlink = $matches[1][0];
        }
        $youtube = file_get_contents($stringlink);
        preg_match_all('/<meta property="og:image" content="(.*)">/',$youtube,$imageurl);
        $returnImage = $imageurl[1][0];
    }
    return array('host'=>$vido_host,'key'=>$returnlink,'thumb'=>$returnImage);
}

function ubbpic($pic1,$pic2,$type) {
	return "<div class='imageshow'><a class='artZoom' href='".$pic2."'><img src='".$pic2."' style='height:100px;'></a>
        </div>";
//	return "<div class='imageshow'><a class='miniImg artZoom' href='javascript:void(0)'><img src='".$pic2."' style='height:100px;'></a>
//        <div class='artZoomBox'>
//        <div class='clearline'></div>
//        <a class='maxImgLink' href='javascript:void(0)'><img src='".$pic1."' class='maxImg'></a>
//        </div>
//        </div>";
}

function sendMail($address,$title,$message)
{
    vendor('PHPMailer.class#phpmailer');
    
    $mail=new PHPMailer();
    
    // 设置PHPMailer使用SMTP服务器发送Email
    $mail->IsSMTP();

    // 设置邮件的字符编码，若不指定，则为'UTF-8'
    $mail->CharSet='UTF-8';

    // 添加收件人地址，可以多次使用来添加多个收件人
    $mail->AddAddress($address);

    // 设置邮件正文
    $mail->MsgHTML($message);

    // 设置邮件头的From字段。
    $mail->From=C('MAIL_ADDRESS');

    // 设置发件人名字
    $mail->FromName=C('MAIL_FROMNAME');

    // 设置邮件标题
    $mail->Subject=$title;

    // 设置SMTP服务器。
    $mail->Host=C('MAIL_SMTP');

    // 设置为"需要验证"
    $mail->SMTPAuth=true;

    // 设置用户名和密码。
    $mail->Username=C('MAIL_LOGINNAME');
    $mail->Password=C('MAIL_PASSWORD');

    // 发送邮件。
    return($mail->Send());
}

function jMail($address, $title, $message) {
	$jmail = new COM('JMail.Message'); 
	$jmail->silent = true; //屏蔽例外错误  
	$jmail->charset = 'gb2312'; //否则中文会乱码  
	$jmail->From = C('MAIL_ADDRESS'); //这里理论上是可以不与发件人地址相同的，但用163的试了几次都不行，改成一样的就可以了  
	$jmail->FromName = C('MAIL_FORMNAME');  
	$jmail->AddRecipient($address); //可添加多个邮件接受者  
	$jmail->ContentType = "Text/html";
	$jmail->Subject = mb_convert_encoding($title, 'gb2312', 'utf8');
	$jmail->Body = mb_convert_encoding($message, 'gb2312', 'utf8');
	$jmail->MailServerUserName = C('MAIL_LOGINNAME'); //发信邮件账号 
	$jmail->MailServerPassword = C('MAIL_PASSWORD'); //账户的密码 
	try{
	    $email = $jmail->Send(C('MAIL_SMTP'));
	    if ($email) {
	    	return true;
	    } else {
	    	return false;
	    }
	} catch (Exception $e){
	    return false;
	}
}